package com.zpy.controller;

import cn.hutool.crypto.Mode;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zpy.pojo.Book;
import com.zpy.pojo.User;
import com.zpy.pojo.UserRole;
import com.zpy.service.BookService;
import com.zpy.service.UserRoleService;
import com.zpy.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.util.Date;
import java.util.List;

@Slf4j
@Controller
public class AccountController {

    @Autowired
    private BookService bookService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;
    @Value("${location}")
    private String location;
    @RequestMapping("toRegister")
    public String toRegister(){
        return "register";
    }

    @RequestMapping("toLogin")
    public String toLogin(){
        return "index";
    }

    @RequestMapping("count")
    public String count(Model model,HttpSession session){
        List<Book> list = bookService.list(null);
        int all=0;
        for (int i = 0; i < list.size(); i++) {
            all=all+1;
        }

        model.addAttribute("all",all);
        String unit = (String) session.getAttribute("unit");
        QueryWrapper<Book>queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("unit",unit);
        List<Book> list1 = bookService.list(queryWrapper);
        int thisUnitBook=0;
        for (int i = 0; i < list1.size(); i++) {
            thisUnitBook=thisUnitBook+1;
        }
        model.addAttribute("thisUnitBook",thisUnitBook);
        return "chart_count";
    }


    @RequestMapping("login")
    public String login(String userName, String userPwd,  Integer role, HttpSession session,Model model){


        if (role==null){
            session.setAttribute("username",userName);
            session.setAttribute("password",userPwd);
            return "libraryMainMenu3";
        }else if (role==1){
            QueryWrapper<User>qw=new QueryWrapper<>();
            qw.eq("username",userName);
            User one2 = userService.getOne(qw);
            if (one2==null){
                model.addAttribute("msg","此用户不存在");
                return "index";
            }
            qw.eq("password",userPwd);
            User one = userService.getOne(qw);
            if (one==null){
                model.addAttribute("msg","用户名或密码错误");
                return "index";
            }else {
                QueryWrapper<UserRole>queryWrapper=new QueryWrapper<>();
                queryWrapper.eq("uid",one.getId());
                queryWrapper.eq("rid",role);
                UserRole one1 = userRoleService.getOne(queryWrapper);
                if (one1==null){
                    model.addAttribute("msg","用户名或密码错误");
                    return "index";
                }
                session.setAttribute("currentUser",userName);
                session.setAttribute("password",userPwd);
                session.setAttribute("image",one.getImage());
                session.setAttribute("number",one.getNumber());
                session.setAttribute("userId",one.getId());
                session.setAttribute("roleId",role);
                session.setAttribute("unit",one.getUnit());
                //设置登录时间
                one.setLoginTime(new Date());
                userService.updateById(one);
                return "libraryMainMenu";
            }
        }else if (role==2){
            QueryWrapper<User>qw1=new QueryWrapper<>();
            qw1.eq("number",userName);
            qw1.eq("password",userPwd);
            User one = userService.getOne(qw1);
            if (one==null){
                model.addAttribute("msg","用户名或密码错误");
                return "index";
            }else {
                QueryWrapper<UserRole>queryWrapper=new QueryWrapper<>();
                queryWrapper.eq("uid",one.getId());
                queryWrapper.eq("rid",role);
                UserRole one1 = userRoleService.getOne(queryWrapper);
                if (one1==null){
                    model.addAttribute("msg","用户名或密码错误");
                    return "index";
                }
                log.info(one.getImage());
                session.setAttribute("currentUser",one.getUsername());
                session.setAttribute("password",userPwd);
                session.setAttribute("image",one.getImage());
                session.setAttribute("userId",one.getId());
                session.setAttribute("number",one.getNumber());
                session.setAttribute("roleId",role);
                session.setAttribute("unit",one.getUnit());
                //设置登录时间
                one.setLoginTime(new Date());
                userService.updateById(one);
                return "libraryMainMenu1";
            }
        }else{
            QueryWrapper<User>qw=new QueryWrapper<>();
            qw.eq("username",userName);
            User one2 = userService.getOne(qw);
            if (one2==null){
                model.addAttribute("msg","此用户不存在");
                return "index";
            }
            qw.eq("password",userPwd);
            User one = userService.getOne(qw);
            if (one==null){
                model.addAttribute("msg","用户名或密码错误");
                return "index";
            }else {
                QueryWrapper<UserRole>queryWrapper=new QueryWrapper<>();
                queryWrapper.eq("uid",one.getId());
                queryWrapper.eq("rid",role);
                UserRole one1 = userRoleService.getOne(queryWrapper);
                if (one1==null){
                    model.addAttribute("msg","用户名或密码错误");
                    return "index";
                }
                session.setAttribute("currentUser",userName);
                session.setAttribute("password",userPwd);
                session.setAttribute("image",one.getImage());
                session.setAttribute("number",one.getNumber());
                session.setAttribute("userId",one.getId());
                session.setAttribute("roleId",role);
                session.setAttribute("unit",one.getUnit());
                //设置登录时间
                one.setLoginTime(new Date());
                userService.updateById(one);
                return "libraryMainMenu2";
            }
        }
    }

    //登出
    @RequestMapping("logout")
    public String logout(HttpSession session){
        //清空session的数据
        session.invalidate();
        //跳转到登录页面
        return "index";
    }

    //跳转到修改个人信息的页面
    @RequestMapping("profile")
    public String profile(HttpServletRequest request, Model model){
        //从session拿到用户名
        String currentUser = (String) request.getSession().getAttribute("currentUser");
        Integer userId = (Integer) request.getSession().getAttribute("userId");
        //条件构造器
        QueryWrapper<User>qw=new QueryWrapper<>();
        //根据姓名查询
        qw.eq("username",currentUser);
        //调用mybatis-plus封装好的getOne()方法
        User one = userService.getOne(qw);
        model.addAttribute("user",one);//在model里存数据
        QueryWrapper<UserRole>queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("uid",userId);
        UserRole userRole = userRoleService.getOne(queryWrapper);
        if (userRole.getRid()==1){
            //跳转到个人信息页面
            return "profile-admin";
        }else if (userRole.getRid()==2){
            return "profile-worker";
        }else{
            return "profile-reader";
        }
    }

    //修改个人信息
    @RequestMapping("updateProfile")
    public String updateAdminProfile(User user, MultipartFile file){
        if (!file.isEmpty()){
            String path=transFile(file);
            user.setImage(path);
        }
        boolean b = userService.updateById(user);
        return "redirect:/profile";

    }

    //上传文件
    private String transFile(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();//获得文件全名
        int index = originalFilename.lastIndexOf(".");//将文件名前后分开
        String suffix = originalFilename.substring(index);//构造后缀
        String prefix =System.nanoTime()+"";//构造前缀
        String path=prefix+suffix;//拼接成文件名
        File file1 = new File(location);//new 一个要下载的路径的file对象
        if (!file1.exists()){//如果电脑上不存在这个目录
            file1.mkdirs();//创建这个目录
        }
        File file2 = new File(file1,path);
        try {
            file.transferTo(file2);//调用上传方法
        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }



}
